from django.shortcuts import render, get_object_or_404, redirect
from django.core.paginator import EmptyPage, Paginator, PageNotAnInteger
from django.core.mail import send_mail
from taggit.models import Tag
from django.db.models import Count
from django.contrib.postgres.search import SearchVectorField
from django.views import View
from haystack.views import SearchView


from .models import Post, Comments
from .forms import EmailPost, CommentForm, SearchForm


def post_list(request, tag_slug=None):
    posts = Post.published.all()
    tag = None
    if tag_slug:
        tag = get_object_or_404(Tag, slug=tag_slug)
        posts = posts.filter(tags__in=[tag])
    paginator = Paginator(posts, 1)
    page = request.GET.get('page')
    try:
        posts = paginator.page(page)
    except PageNotAnInteger:
        posts = paginator.page(1)
    except EmptyPage:
        posts = paginator.page(paginator.num_pages)
    return render(request, 'blog_article/list.html', context={'posts': posts, 'page': page, 'tag': tag})


def post_detail(request, post_pk):
    post = get_object_or_404(Post, id=post_pk)
    comments = post.comments.filter(activate=True)
    new_comment = None
    if request.method == 'POST':
        comment_form = CommentForm(data=request.POST)
        if comment_form.is_valid():
            new_comment = comment_form.save(commit=False)
            new_comment.post = post
            new_comment.save()
    else:
        comment_form = CommentForm()
    post_tags_ids = post.tags.values_list('id', flat=True)
    similar_posts = Post.published.filter(tags__in=post_tags_ids).exclude(id=post.id)
    similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags', 'publish')
    return render(request, 'blog_article/detail.html', context={'post': post, 'comments': comments,
                                                                'new_comment': new_comment,
                                                                'comment_form': comment_form,
                                                                'similar_posts': similar_posts})


def post_share(request, post_pk):
    """
    存在问题：在get的时候传入了参数，但是到了 页面填写表单之后，并没有地方有存在传递了ppost_pk的地方，那么为什么还可以？
    我好像猜到了什么，发送表单到的是当前页面，所以share/2/符合url里面的2
    :param request:
    :param post_pk:
    :return:
    """
    post = get_object_or_404(Post, id=post_pk)
    send = False
    if request.method == 'POST':
        form = EmailPost(request.POST)
        if form.is_valid():
            #如果没有经过验证，那么只会包含有效字段
            cd = form.cleaned_data
            post_url = request.build_absolute_uri(post.get_absolute_url())
            subject = '{} ({})recomends you reading"{}"'.format(cd['name'], cd['email'], post.title)
            message = 'read "{}" at {}\n\n{}\'s comments:{} '.format(post.title, post_url, cd['name'], cd['comments'])
            send_mail(subject, message, '2014593913@qq.com', [cd['to']])
            send = True
    else:
        form = EmailPost()
    return render(request, 'blog_article/share.html', context={'post': post, 'form': form, 'send': send})

#
# def post_search(request):
#     form = SearchForm()
#     query = None
#     results = []
#     if 'query' in request.GET:
#         form = SearchForm(request.GET)
#         if form.is_valid():
#             query = form.cleaned_data['query']
#             results = Post.objects.annotate(search=SearchVectorField('title', 'body'),).filter(search=query)
#     return render(results, 'blog_article/../templates/search/search.html', context={'form': form,
#                                                                 'query': query,
#                                                                 'results': results})
#
# class MySearchView(SearchView):
#     def extra_context(self):
#         context = super(MySearchView, self).extra_context()
#         search_post = Post.objects.filter()
# Create your views here.
